<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import customNavbar from '../index/components/customNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'
import {
  getHomeBannerApi,
  getHomeCategoryApi,
  getHomeHotPanelApi,
  getHomeGuessApi,
} from '@/services/home'
import type { BannerItem, CategoryItem, HotItem, GuessItem } from '@/types/home'
import type { XtxGuessInstance } from '@/components/components'
import { useGuessList } from '../../composables/index'
const imgData = ref<BannerItem[]>()
const CategoryData = ref<CategoryItem[]>()
const HotPanelData = ref<HotItem[]>()
const isTriggered = ref(false)
const { guessRef, onScrolltolower } = useGuessList()
// 获取banner
const getHomeBannerData = async () => {
  const res = await getHomeBannerApi()
  console.log(res)
  imgData.value = res.result
}
// 获取分类
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryApi()
  CategoryData.value = res.result!
  console.log(res.result)
}
// 获取前台推荐
const getHomeHotPanelData = async () => {
  const res = await getHomeHotPanelApi()
  HotPanelData.value = res.result
  console.log(res)
}
// 底部滑动加载更多
// const scrollToloWerChange = () => {
//   uni.showLoading({
//     title: '加载中',
//   })
//   guessRef.value!.getHomeGuessData()
//   uni.hideLoading()
// }
// 下拉刷新
const refresherrefreshChange = async () => {
  isTriggered.value = true
  guessRef.value!.resetData()
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotPanelData(),
    onScrolltolower(),
  ])
  isTriggered.value = false
}
const loading = ref(false)
onLoad(async () => {
  loading.value = true
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotPanelData(),
    onScrolltolower(),
  ])
  loading.value = false
})
</script>

<template>
  <!-- 首页导航栏 -->
  <customNavbar />
  <scroll-view
    scroll-y
    class="scroll-view"
    @scrolltolower="onScrolltolower"
    refresher-enabled
    :refresher-triggered="isTriggered"
    lower-threshold="100"
    @refresherrefresh="refresherrefreshChange"
  >
    <PageSkeleton v-if="loading" />
    <template v-else>
      <!-- 首页轮播图 -->
      <XtxSwiper :data="imgData" />
      <!-- 首页分类 -->
      <CategoryPanel :CategoryData="CategoryData" />
      <!-- 首页推荐 -->
      <HotPanel :HotPanelData="HotPanelData" />
      <!-- 猜你喜欢 -->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f7f7f7;
}
.scroll-view {
  flex: 1;
}
</style>
